from datetime import datetime

from interface_item.api.base_api import BaseApi
from interface_item.utils.logger import logger
from interface_item.utils.read_data import r_data

import os

'''
业务层封装，公共api
'''

BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
TOKEN_PATH = os.path.join(BASE_PATH, 'data', 'token.yaml')
ENV_PATH = os.path.join(BASE_PATH, "env.ini")
BASE_URL = r_data.load_ini(ENV_PATH)["test"]["base_url"]


class FeiShuApi(BaseApi):

    def __init__(self):
        self.token_info = self._get_loc_token()
        self.token = self.get_token()

    @staticmethod
    def _get_loc_token():
        # 获取本地存的token信息
        loc_token = r_data.load_yaml(TOKEN_PATH)
        return loc_token

    def get_token(self):
        # 获取当前时间戳
        now_timestamp = int(datetime.now().timestamp())
        logger.debug(f"本地存储的token失效时间为：{self.token_info.get('expire_remark')}")
        # 获取本地存的token对应的失效时间
        expire_deadline = self.token_info.get("expire_deadline")

        # 已经过了失效时间,重新获取token
        if now_timestamp >= expire_deadline:
            logger.debug("本地token已经失效，需要重新获取")
            token = self._get_new_token()
            logger.debug(f"重新获取token成功：{token}")
        else:
            logger.debug("本地token没有失效")
            token = self.token_info.get("token")
        return token

    def _get_new_token(self):
        '''
        :return: 获取token信息
        '''

        token_url = BASE_URL + "/auth/v3/tenant_access_token/internal"
        app_id = self.token_info.get("app_id")
        app_secret = self.token_info.get("app_secret")

        data = {
            "app_id": app_id,
            "app_secret": app_secret
        }

        res = self.base_request(url=token_url, method="post", json=data).json()
        token = res.get("tenant_access_token")  # 获取token
        duration = res.get("expire")  # 获取token持续有效时间
        # 计算出token的失效时间, 获取系统当前时间转为时间戳，然后时间戳转为整型加上token持续有效时间
        expire_deadline = int(datetime.now().timestamp()) + duration
        # 把计算出来的失效时间转为格式化时间，expire_dealine是整型，需要先转为时间戳然后再格式化
        expire_remark = datetime.fromtimestamp(expire_deadline).strftime("%Y-%m-%d %H:%M:%S")

        logger.debug(f"获取新token=====> token:{token}, 失效时间：{expire_remark}")

        # 更新token信息，字典键值对更新使用update
        self.token_info.update(
            {
                "token": token,
                "duration": duration,
                "expire_deadline": expire_deadline,
                "expire_remark": expire_remark
            }
        )
        r_data.save_yaml(self.token_info, TOKEN_PATH)
        return token

    def fs_requests(self, method, url='', **kwargs):
        url = BASE_URL + url
        # 判断请求中是否有请求头,给请求头添加token信息
        if "headers" in kwargs:
            kwargs["headers"]["Authorization"] = f"Bearer {self.token}"
        else:
            kwargs["headers"] = {"Authorization": f"Bearer {self.token}"}

        res = self.base_request(method=method, url=url, **kwargs)
        return res
